<template>
    <div class="view-component" :id="detail.identifier" ref="xcomp">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item label="设备名称" prop="identify">
                <el-input v-model="queryParams.identify" placeholder="请输入设备名称" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="时间">
                <div>
                    <span @click="timesDataFun(1)" :class="{ 'timesColror': timesData == 1 }"
                        class="timesCliass">半小时</span>
                    <span @click="timesDataFun(2)" :class="{ 'timesColror': timesData == 2 }"
                        class="timesCliass">6小时</span>
                    <span @click="timesDataFun(3)" :class="{ 'timesColror': timesData == 3 }"
                        class="timesCliass">24小时</span>
                    <span @click="timesDataFun(4)" :class="{ 'timesColror': timesData == 4 }"
                        class="timesCliass">一个月</span>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :height="300" :data="logList">
            <el-table-column type="index" label="序列" width="55" align="center" />
            <el-table-column label="设备" align="center" prop="modelName" />
            <el-table-column label="设置值" align="center" prop="funValue" />
            <el-table-column label="下发时间" align="center" prop="createTime" />
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        <div v-show="false">{{ animateChange }}</div>

    </div>
</template>

<script>
import Vue from 'vue';
import { mapState } from 'vuex';

import BaseView from './View.vue';
import topoUtil from '@/utils/topo/topo-util';
import { getAnimate } from '@/utils/topo/anime';
import { getComponent } from '@/api/scada/component';
import { listLog } from '@/api/iot/functionLog';
export default {
    name: 'view-component',
    extends: BaseView,
    dicts: ['iot_function_type', 'iot_yes_no'],
    data() {
        return {
            data: {
                componentTemplate: '',
                componentStyle: '',
                componentScript: '',
            },
            queryParams: {
                pageNum: 1,
                pageSize: 5,
                identify: '',
                startTime: '',
                endTime: '',
                id: '',
            },
            // 遮罩层
            loading: true,
            // 设备服务下发日志表格数据
            logList: [],
            // 总条数
            total: 0,
            // 时间选择
            timesData: 1,
        };
    },
    computed: {
        ...mapState({
            mqttData: (state) => state.topoEditor.mqttData,
        }),
        animateChange() {

            if (this.mqttData) {
                // this.getList(this.mqttData.serialNumber)
                // 动画初始化
                if (
                    this.detail.dataAction.serialNumber &&
                    this.detail.dataAction.identifier &&
                    this.detail.dataAction.paramJudge &&
                    this.detail.dataAction.paramJudgeData != undefined &&
                    this.mqttData.serialNumber == this.detail.dataAction.serialNumber
                ) {
                    const message = this.mqttData.message.find((item) => item.id === this.detail.dataAction.identifier);
                    if (message) {
                        let val = message.value;
                        let isGd = topoUtil.judgeSize(this.detail.dataAction.paramJudge, val, this.detail.dataAction.paramJudgeData);
                        if (isGd) {
                            if (this.detail.dataBind.xyAction) {
                                // 显隐判断
                                getAnimate().set(document.getElementById(this.detail.identifier), {
                                    display: 'block',
                                });
                            }
                            if (this.animateView) {
                                this.animateView.play();
                            }
                        } else {
                            if (this.detail.dataBind.xyAction) {
                                // 显隐判断
                                getAnimate().set(document.getElementById(this.detail.identifier), {
                                    display: 'none',
                                });
                            }
                            if (this.animateView) {
                                this.animateView.pause();
                            }
                        }
                    }
                }
            }
        },
    },
    mounted() {
        // this.initEchart();

    },
    created() {
        this.isGetFun();
        this.getList();
    },
    methods: {
        /** 查询设备服务下发日志列表 */
        getList(id) {
            this.loading = false;
            this.queryParams.serialNumber = this.mqttData.serialNumber;
            listLog(this.queryParams).then((response) => {
                this.logList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 计算时间
        calculateTime() {
            const now = new Date();
            const halfHourAgo = new Date(now.getTime() - 30 * 60 * 1000);
            const sixHoursAgo = new Date(now.getTime() - 6 * 60 * 60 * 1000);
            const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
            const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());

            return {
                now: this.formatDate(now),
                halfHourAgo: this.formatDate(halfHourAgo),
                sixHoursAgo: this.formatDate(sixHoursAgo),
                twentyFourHoursAgo: this.formatDate(twentyFourHoursAgo),
                oneMonthAgo: this.formatDate(oneMonthAgo)
            };
        },
        // 格式化日期为 年月日 时分秒
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        timesDataFun(val) {
            this.timesData = val;
            const { now, halfHourAgo, sixHoursAgo, twentyFourHoursAgo, oneMonthAgo } = this.calculateTime();
            switch (val) {
                case 1:
                    this.queryParams.beginTime = halfHourAgo;
                    this.queryParams.endTime = now;
                    break;
                case 2:
                    this.queryParams.beginTime = sixHoursAgo;
                    this.queryParams.endTime = now;
                    break;
                case 3:
                    this.queryParams.beginTime = twentyFourHoursAgo;
                    this.queryParams.endTime = now;
                    break;
                case 4:
                    this.queryParams.beginTime = oneMonthAgo;
                    this.queryParams.endTime = now;
                    break;
                default:
                    this.queryParams.beginTime = '';
                    this.queryParams.endTime = '';
                    break
            }

        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        isGetFun() {

        },
        initEchart() {
            let id = this.detail.dataBind.componentId;
            this.getComponentDataById(id);
        },
        // 获取自定义Component详情
        getComponentDataById(id) {
            getComponent(id).then((res) => {
                if (res.code === 200) {
                    this.data = res.data;
                    this.loadData();
                }
            });
        },
        loadData() {
            let template = this.data.componentTemplate;
            if (!template) return;
            let styleCss = this.data.componentStyle;
            let style = document.createElement('style');
            style.innerHTML = styleCss;
            document.head.appendChild(style);
            let script = this.data.componentScript;
            if (script) {
                script = script.replace(/export default/, 'return');
            }
            let obj = new Function(script)();
            obj.template = template;
            let Profile = Vue.extend(obj);
            if (this.$refs.xcomp.innerHTML) {
                this.$refs.xcomp.innerHTML = '';
            }
            let newDiv = document.createElement('div');
            newDiv.setAttribute('id', `xcomp-${this.data.id}`);
            this.$refs.xcomp.appendChild(newDiv);
            new Profile().$mount(`#xcomp-${this.data.id}`);
        },
    },
};
</script>

<style lang="scss">
.view-component {
    height: 100%;
    width: 100%;
    padding: 10px;
    overflow-y: auto;
}

.timesCliass {
    padding: 0 10px;
    cursor: pointer;
}

.timesColror {
    color: #00baff;
}
</style>
